package com.egao.common.module.guidance.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.company.utils.CompanyUtil;
import com.egao.common.module.guidance.entity.Lecture;
import com.egao.common.module.guidance.entity.LectureApply;
import com.egao.common.module.guidance.entity.vo.LectureApplyVO;
import com.egao.common.module.guidance.mapper.LectureApplyMapper;
import com.egao.common.module.guidance.mapper.LectureMapper;
import com.egao.common.module.guidance.service.LectureApplyService;
import com.egao.common.module.guidance.service.LectureService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.publicly.entity.ApplyButtonVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 就业讲座报名接口实现类
 *
 * @author pyx
 */
@Service
public class LectureApplyServiceImpl extends ServiceImpl<LectureApplyMapper, LectureApply> implements LectureApplyService {
    @Autowired
    private LectureService lectureService;
    @Autowired
    private StudentService studentService;
    @Autowired(required = false)
    private LectureMapper lectureMapper;

    @Override
    public List<LectureApply> listGetLecture(Integer id, Integer state) {
        return baseMapper.listGetLecture(id, state);
    }

    @Override
    public JsonResult updateLectureApply(LectureApply lectureApply) {
        if (lectureApply == null) {
            throw new ParameterException("参数对象为空");
        }

        if (lectureApply.getState() == null) {
            throw new ParameterException("审核状态不能为空");
        }

        int success = 0;
        // 批量审核
        if (!StrUtil.isBlank(lectureApply.getIds())) {
            String[] ids = lectureApply.getIds().split(",");
            UpdateWrapper uw =new UpdateWrapper();
            uw.in("id", ids);
            success = baseMapper.update(lectureApply, uw);
        } else {
            success = baseMapper.updateById(lectureApply);
        }


        if (success > 0) {
            return JsonResult.ok("审核成功");
        }

        return JsonResult.error("审核失败");
    }

    @Override
    public JsonResult insertLectureApply(Integer lectureId, Integer userId) {
        if (lectureId == null) {
            return JsonResult.error("讲座不存在");
        }

        if (userId == null) {
            return JsonResult.error("请先登录");
        }

        Student student = studentService.getByUserId(userId);
        if (student == null) {
            return JsonResult.error("该学生账号不存在");
        }

        //获取报名状态
        JsonResult jsonResult = applyVerify(lectureId, student.getId());

        ApplyButtonVO applyButton = (ApplyButtonVO) jsonResult.get("applyButton");
        ApplyButtonVO cancelButton = (ApplyButtonVO) jsonResult.get("cancelButton");

        //讲座报名
        if (applyButton != null && applyButton.getButtonState() == 0) {
            //获取报名讲座信息
            LectureApply lectureApply = (LectureApply) jsonResult.get("lectureApply");
            Lecture lecture = (Lecture) jsonResult.get("lecture");

            if (lectureApply == null && lecture.getApplyPass() == 1) {
                LectureApply apply = new LectureApply();
                apply.setState(1);
                apply.setStudentId(student.getId());
                apply.setLectureId(lectureId);
                baseMapper.insert(apply);

                //更新讲座报名人数信息
                Integer num = baseMapper.listGetLecture(lectureId, 1).size();
                lecture.setAuditApproveNum(num);
                lectureMapper.updateById(lecture);

                return JsonResult.ok("报名成功");
            } else {
                LectureApply apply = new LectureApply();
                apply.setState(0);
                apply.setStudentId(student.getId());
                apply.setLectureId(lectureId);
                baseMapper.insert(apply);

                //更新讲座报名人数信息
                Integer num = baseMapper.listGetLecture(lectureId, 0).size();
                lecture.setAuditAwaitNum(num);
                lectureMapper.updateById(lecture);

                return JsonResult.ok("报名成功,请等待审核");
            }
        }

        return jsonResult;
    }

    @Override
    public JsonResult applyVerify(Integer lectureId, Integer studentId) {
        //1.判断是否报过名
        //根据讲座id和学生id查找报名信息
        QueryWrapper<LectureApply> laWrapper = new QueryWrapper<>();
        laWrapper.eq("lecture_id", lectureId).eq("student_id", studentId);
        LectureApply lectureApply = baseMapper.selectOne(laWrapper);

        //根据讲座id查询讲座信息
        Lecture lecture = lectureService.getId(lectureId);

        if (lecture == null) {
            throw new ParameterException("讲座信息为空");
        }

        ApplyButtonVO applyButtonVO = new ApplyButtonVO();
        ApplyButtonVO cancelButtonVO = new ApplyButtonVO();
        cancelButtonVO.setButtonText("取消");

        //1.报名表有记录的情况
        if (lectureApply != null && lectureApply.getState() == 3) {
            applyButtonVO.setButtonText("取消报名后不可在报名");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        } else if (lectureApply != null && lectureApply.getState() == 2) {
            applyButtonVO.setButtonText("审核未通过");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        } else if (lectureApply != null && lectureApply.getState() == 1) {
            applyButtonVO.setButtonText("已报名");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(0);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        } else if (lectureApply != null && lectureApply.getState() == 0) {
            applyButtonVO.setButtonText("审核中");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(0);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        //2.报名表无记录的情况
        Integer num = lecture.getAuditAwaitNum() + lecture.getAuditApproveNum();
        if (lectureApply == null && (lecture.getApplyNum() - num) <= 0) {
            applyButtonVO.setButtonText("报名人数已满");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        //拿到当前时间
        Date now = DateUtil.date(Calendar.getInstance());
        //判断是否达到报名时间
        if (lectureApply == null && now.compareTo(lecture.getApplyEndTime()) == 1) {
            applyButtonVO.setButtonText("报名时间已过");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }
        if (lectureApply == null && now.compareTo(lecture.getStartTime()) == 1) {
            applyButtonVO.setButtonText("讲座已开始");
            applyButtonVO.setButtonState(1);
            cancelButtonVO.setButtonState(2);
            return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO);
        }

        applyButtonVO.setButtonText("可以报名");
        applyButtonVO.setButtonState(0);
        cancelButtonVO.setButtonState(2);
        return JsonResult.ok("操作成功").put("applyButton", applyButtonVO).put("cancelButton", cancelButtonVO).put("lectureApply", lectureApply).put("lecture", lecture);
    }

    @Override
    public JsonResult cancelApply(Integer lectureId, Integer userId) {
        if (lectureId == null) {
            return JsonResult.error("讲座不存在");
        }

        if (userId == null) {
            return JsonResult.error("请先登录");
        }

        Student student = studentService.getByUserId(userId);
        if (student == null) {
            return JsonResult.error("该学生账号不存在");
        }

        QueryWrapper<LectureApply> lectureApplyQueryWrapper = new QueryWrapper<>();
        lectureApplyQueryWrapper.eq("student_id", student.getId()).eq("lecture_id", lectureId);
        LectureApply lectureApply = baseMapper.selectOne(lectureApplyQueryWrapper);

        if (lectureApply == null) {
            return JsonResult.error("没有查到报名信息");
        }

        lectureApply.setState(3);
        updateById(lectureApply);

        //处理审核人数变化
        Lecture lecture = lectureMapper.selectById(lectureApply.getLectureId());
        Integer cancelNum = baseMapper.listGetLecture(lectureId, 3).size();
        lecture.setCancelNum(cancelNum);
        Integer auditAwaitNum = baseMapper.listGetLecture(lectureId, 0).size();
        lecture.setAuditAwaitNum(auditAwaitNum);
        Integer auditApproveNum = baseMapper.listGetLecture(lectureId, 1).size();
        lecture.setAuditApproveNum(auditApproveNum);
        lectureMapper.updateById(lecture);

        return JsonResult.ok("取消报名成功");
    }

    @Override
    public List<LectureApplyVO> listApplyPage(PageParam<LectureApplyVO> pageParam, Integer loginUserId) {
        //处理举办时间段数据
        pageParam = (PageParam<LectureApplyVO>) CompanyUtil.putApplyTime(pageParam);

        Integer studentId = null;
        Student student = studentService.getByUserId(loginUserId);
        if (student == null) {
            throw new ParameterException("学生信息不存在");
        }
        studentId = student.getId();

        //如果card为0查询所有讲座信息
        if ("0".equals(pageParam.getPageData().get("card"))) {
            return baseMapper.listLecture(pageParam);
        } else {
            return baseMapper.listStudentLecture(pageParam, studentId);
        }

    }

    @Override
    public LectureApply studentApply(Integer studentId, Integer lectureId) {
        QueryWrapper<LectureApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id",studentId).eq("lecture_id",lectureId);
        return baseMapper.selectOne(queryWrapper);
    }
}
